package Thread.SeampLock;

import org.w3c.dom.css.Counter;

import java.util.Arrays;
import java.util.concurrent.locks.StampedLock;

public class Main {
    public static void main(String[] args) {
        Point p=new Point();
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                for (int j = 0; j < 1000; j++) {
                    p.move(1,1);
                }
            }).start();
        }
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                System.out.println(p.distanceFormOrigin());
            }).start();
        }

    }
}

class Point{
    private final StampedLock lock = new StampedLock();
    private double x;
    private double y;

    public void move(double x, double y){
        long stamp = lock.writeLock();
        try {
            this.x += x;
            this.y += y;
        }finally {
            lock.unlockWrite(stamp);
        }
    }

    public double distanceFormOrigin(){
        long stamp = lock.tryOptimisticRead();

        double currentx = x;
        double currenty = y;
        if (!lock.validate(stamp)) {
            stamp = lock.readLock();
            try{
                currentx = x;
                currenty = y;
            }finally {
                lock.unlockRead(stamp);
            }
        }
        System.out.println(Arrays.toString(new double[]{currentx, currenty}));
        return Math.sqrt(currentx*currentx + currenty*currenty);
    }
}